tinyMCEPopup.requireLangPack();

var StyleLibraryTableDialog = {
	init : function() {
		var f = document.forms[0];

		document.getElementById('previewbg_pickcontainer').innerHTML = getColorPickerHTML('previewbg_pick','previewbg');

		// Panels
		fntFont.init(tinyMCEPopup.editor);
		cellProp.init(tinyMCEPopup.editor);
		BorderPicker.init(tinyMCEPopup.editor);
		
		TinyMCE_EditableSelects.init();
		
		initDesigner("dialog");
	}
};

tinyMCEPopup.onInit.add(StyleLibraryTableDialog.init, StyleLibraryTableDialog);

var tableCollapseCss; // stores table's.cssText for delayed collapse update.
var tableStyleRefence; // pointer to table's style in css file for delayed collapse update.

// designer.rules array:
// [0] : table
// [1] : td,th
// [2] : td alt, th, alt
// [3] : th
// [4] : th alt
// [5] : caption

function initDesigner(caller)
{
	// Run only if all loaded
	switch(caller) {
		case "frame":
			frameLoaded = true;
			break;
		case "dialog":
			dialogLoaded = true;
			break;
		case "css":
			if(tinymce.isGecko) { return; }  // Never runs. Gecko does not call this way.
			cssLoaded = true;
			break;
	}
	if(!frameLoaded || !dialogLoaded || (!tinymce.isGecko && !cssLoaded)) {
		return;
	}

	conflictManager = new borderConflictManager();

	// Configure which rules allow what properties.
	
	// All has border except caption
	designer.rules[0].properties.initBorder();
	designer.rules[1].properties.initBorder();
	designer.rules[2].properties.initBorder();
	designer.rules[3].properties.initBorder();
	designer.rules[4].properties.initBorder();
	
	// All has font, except table(0)
	designer.rules[1].properties.initFont();
	designer.rules[2].properties.initFont();
	designer.rules[3].properties.initFont();
	designer.rules[4].properties.initFont();
	designer.rules[5].properties.initFont();
	
	// All has cellprop except and caption(5) (but 'table' has less)
	designer.rules[0].properties.initCellProp();
	designer.rules[0].properties.killProperty('text-indent');
	designer.rules[0].properties.killProperty('text-align');
	designer.rules[0].properties.killProperty('vertical-align');
	designer.rules[1].properties.initCellProp();
	designer.rules[2].properties.initCellProp();
	designer.rules[3].properties.initCellProp();
	designer.rules[4].properties.initCellProp();
	
	// Background images 
	designer.rules[0].properties.initBackground();
	designer.rules[1].properties.initBackground();
	designer.rules[2].properties.initBackground();
	designer.rules[3].properties.initBackground();
	designer.rules[4].properties.initBackground();

	// Special properties for table
	designer.rules[0].properties.initProperty('border-collapse');
	designer.rules[0].properties.initProperty('background-color');
	designer.rules[0].properties.initProperty('border-spacing');
	
	// Load necessary CSS files	in preview frame
	loadPreviewStyles(window.frames['demoFrame'].document, 
		tinyMCEPopup.editor.getParam("stylelibrary_previewstyles", 
			tinyMCEPopup.editor.getParam("content_css")));

	// Parse input, get dom pointers, create dom rules.
	designer.init(window.frames['demoFrame'].document, "wysiwyg");
	
	previewSettings.switchLorem(false, true);
	previewSettings.demoBgInit();
	previewSettings.showTableHeaders();
	setDemoClass();
	previewSettings.selectDemoTable();
	mcTabs.showTab(document.getElementById('task_tablestyle'));
	setTask('tablestyle');
	detectCollapse()

	updateDemo();
}

function updateDemo()
{
	var output = document.getElementById("hdnCssOutput");
	
	// Store border collapse for delayed update
	var collapse = designer.rules[0].getProperty('border-collapse');
	designer.rules[0].setProperty('border-collapse', 'separate');
	
	designer.generateOutput();
	designer.updateCssDom();
	output.value = removeNL(designer.getCss());
	
	if(DEBUGJS)
	{
		alert(output.value);
	}

	// Delayed collapse update to give browers a real update		
	if(collapse == 'collapse')
	{
		designer.rules[0].setProperty('border-collapse', 'collapse');
		designer.generateOutput();
		
		tableCollapseCss = removeNL(designer.rules[0].cssTextOut);
		output.value = removeNL(designer.getCss());
		
		tableStyleRefence = designer.ruleManager.searchRules[0].rules[0].style; // Note: this won't work if the rule may contain more selectors.
		setTimeout(postponedUpdateCollapse, 100);
	}
	
	previewSettings.switchCollapseNote();
	//FIXME: Checkconflicts does not work since removal of "types" [ WPS 5.4 OK - Lion - Low priorty ]
	//checkConflicts();
}

// Timed function to delay setting the border-collapse property (browsers update better this way)
function postponedUpdateCollapse()
{
	tableStyleRefence.cssText = tableCollapseCss;
}

// Set the loaded class name on demo table.
function setDemoClass()
{
	var styleName = getStyleName();
	var target = window.frames['demoFrame'].document;

	jQuery("div[id^=demoTable] table",target).attr('class',styleName);
}

// BORDER CONFLICT RESOLTIION

function checkConflicts()
{
	conflictManager.init();
	
	var outerSide = 'top';
	var innerSide = 'top';
	
	/* GAPS */
	
	// Table border & table bg
	conflictManager.checkBorderGaps(designer.rules[0], designer.rules[0], outerSide, 
		tinyMCEPopup.editor.getLang('stylelibrary_dlg.conflict_gap_table_table'));
	
	// Table border & cell bg
	if(designer.rules[0].getProperty('border-collapse') != 'separate')
	{
		conflictManager.checkBorderGaps(designer.rules[0], designer.rules[1], outerSide,
			tinyMCEPopup.editor.getLang('stylelibrary_dlg.conflict_gap_table_cell'));
	}
	// Cell border & table bg
	conflictManager.checkBorderGaps(designer.rules[1], designer.rules[0], innerSide,
		tinyMCEPopup.editor.getLang('stylelibrary_dlg.conflict_gap_cell_table'));
	// Cell border & cell bg
	conflictManager.checkBorderGaps(designer.rules[1], designer.rules[1], innerSide,
		tinyMCEPopup.editor.getLang('stylelibrary_dlg.conflict_gap_cell_cell'));
	
	/* TABLE vs TD border (outer border) */
	
	// Outer border must be wider.
	if(designer.rules[0].getProperty('border-collapse') != 'separate')
	{
		conflictManager.checkOuterBorder(designer.rules[0], designer.rules[1], outerSide, innerSide,
			tinyMCEPopup.editor.getLang('stylelibrary_dlg.conflict_outer_border'));
	}
	
	conflictManager.render();
}

// Update collapse and border-spacing from values in the two input fields.
function updateCollapse()
{
	var chkCollapse = document.getElementById("chkCollapse");
	var tRule = designer.rules[0];
	
	if(chkCollapse.checked)
	{
		$("#tablecellspacing").hide();
		tRule.setProperty("border-collapse", "collapse");
		tRule.setProperty("border-spacing", "0");
		// FIXME: This should somehow hide killPropety padding, radius, and the ELSE should add it back?
	}
	else
	{
		$("#tablecellspacing").show();
		tRule.setProperty("border-collapse", "separate");
		var space = document.getElementById("ddlCellSpacing").value;
		tRule.setProperty("border-spacing", space + (space === "" ? "" : "px"));
	}
	updateDemo();
}

// Set the collapse and border-spacing input fields from table data.
function detectCollapse()
{
	var chkCollapse = document.getElementById("chkCollapse");
	var tRule = designer.rules[0];
	
	chkCollapse.checked = tRule.getProperty("border-collapse") == "collapse";
	document.getElementById("ddlCellSpacing").value = tRule.getProperty("border-spacing").replace("px", "");
	if(chkCollapse.checked)
	{
		$("#tablecellspacing").hide();
	} else {
		$("#tablecellspacing").show();
	}
}

// ****** EVENTS ********

function taskChanged()
{
	var task = getTask();

	switch(task) {
		case "tablestyle":
			BorderPicker.initFromRule(designer.rules[0]);
			$("#fldPickFont").hide();
			cellProp.initFromRule(designer.rules[0]);
			break;
		case "cell":
			BorderPicker.initFromRule(designer.rules[1]);
			fntFont.initFromRule(designer.rules[1]);
			cellProp.initFromRule(designer.rules[1]);
			break;
		case "alt":
			BorderPicker.initFromRule(designer.rules[2]);
			fntFont.initFromRule(designer.rules[2]);
			cellProp.initFromRule(designer.rules[2]);
			break;
		case "header":
			BorderPicker.initFromRule(designer.rules[3]);
			fntFont.initFromRule(designer.rules[3]);
			cellProp.initFromRule(designer.rules[3]);
			break;
		case "headeralt":
			BorderPicker.initFromRule(designer.rules[4]);
			fntFont.initFromRule(designer.rules[4]);
			cellProp.initFromRule(designer.rules[4]);
			break;
		case "caption":
			$("#fldPickBorder").hide();
			fntFont.initFromRule(designer.rules[5]);
			$("#fldPickCellProp").hide();
			break;
	}

	// Some tasks hide some panels, show them if not those tasks
	if(task != "caption" && task != "tablestyle") {
		$("#fldPickCellProp").show();
	}
	if(task != "tablestyle") {
		$("#fldPickFont").show();
	}
	if(task != "caption") {
		$("#fldPickBorder").show();
	}
	
	// Switch to left headers if editing alt header cell
	if(task == "headeralt" && 
		(getSelectValue(document.forms[0], "ddlDemoType") != "2" && 
			getSelectValue(document.forms[0], "ddlDemoType") != "3"))
	{
		selectByValue(document.forms[0], "ddlDemoType", "3");
		previewSettings.selectDemoTable();
	}
}
